package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.entity.Collection;
import com.antdesignbackend.backend.entity.entityVo.RoomVo;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2020/7/7.
 */
@Controller
@RequestMapping("/")
public class ActionController {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    MiddlecommandService middlecommandService;
    @Autowired
    IAppointmentService appointmentService;
    @Autowired
    IRoomService roomService;
    @Autowired
    IShopService shopService;
    @Autowired
    MeterService meterService;
    @Autowired
    CommandService commandService;
    @Autowired
    ActionService actionService;
    SimpleDateFormat formattime = new SimpleDateFormat("yyyyMMddHHmmss");
    SimpleDateFormat formatdata = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 小程序 开门码
     */
    @GetMapping("/openCode")
    @ResponseBody
    public List<Object>  openCode(@RequestParam(value = "openId",required = false) String openId,@RequestParam(value = "userId",required = false) String userId, HttpServletRequest request){
        List<Object> data=new ArrayList<>();
        try {

            Date beginDate = CalendarDate.addDate(new Date(), "min", 30);
            if(openId==null || openId.equals(""))
            {
                //那从user表获取openid
                HttpSession session = request.getSession();
                if(session.getAttribute("openid")!=null)
                  openId=session.getAttribute("openid").toString();
            }
            //查询这个微信的预约 openId
            QueryWrapper<Appointment> wrapper=new QueryWrapper<>();
            wrapper.eq("WeChat",openId);
            wrapper.eq("state",1);
            //  wrapper.lt("StartTime",beginDate);
            wrapper.gt("EndTime",new Date());
            List<Appointment> list=appointmentService.list(wrapper);
            if(list.size()==0) return data;
            Date nowdate=new Date();
            for (Appointment dataitem:list) {
                Date begin=dataitem.getStartTime();
                Date end=dataitem.getEndTime();
                // if (DateTime.Now >= begin.AddMinutes(-15) && DateTime.Now <= end && !string.IsNullOrEmpty(aid.ToString()))
                if(nowdate.after(CalendarDate.addDate(begin,"min",-30)) && nowdate.before(end))
                {
                    //说明有预约
                    //获取所有房间信息
                    Room roomdata=roomService.getById(dataitem.getRoomId());
                    Shop shopdata=shopService.getById(roomdata.getShopId());
                    //result="AB|"+formattime.format(dataitem.getStartTime())+"|"+formattime.format(dataitem.getEndTime())+"|"+dataitem.getRoomId()+"|"+dataitem.getId()+"|"+openId;
                   String result="AB|"+formattime.format(dataitem.getStartTime())+"|"+formattime.format(dataitem.getEndTime())+"|"+dataitem.getRoomId()+"|"+dataitem.getId();

                    //获取所有房间信息
                    Map<String,String> map=new HashMap<>();
                    map.put("shopName",shopdata.getName());
                    map.put("shopAddress",shopdata.getAddress());
                    map.put("roomName",roomdata.getName());
                    map.put("appointDate",formatdata.format(dataitem.getAppointDate()));
                    map.put("beginTime",dataitem.getStartInt().toString().substring(0,2)+":"+dataitem.getStartInt().toString().substring(2,4));
                    map.put("endTime",dataitem.getEndInt().toString().substring(0,2)+":"+dataitem.getEndInt().toString().substring(2,4));

                    map.put("code",result);
                    data.add(map);
                }
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }

        return data;
    }
    /**
     * 小程序 扫码开门
     */
    @GetMapping("/SendAction")
    @ResponseBody
    public void SendAction(@RequestParam(value = "txt",required = true) String txt,@RequestParam(value = "topic",required = false) String topic){
        String result="";
        try {
            Date starttime=new Date();
            Date endtime=new Date();
          //  Date beginDate = CalendarDate.addDate(new Date(), "min", -30);
            log.info("扫码开门txt："+txt+",topic:"+topic);
            String[] str=txt.split("|");
            if(str.length<4) return;
            if(!str[0].equals("AB"))return;
            String roomid=str[3];
            String appointid=str[4];

            Date nowdate=new Date();
            //查询这个微信的预约 openId
            Appointment dataitem=appointmentService.getById(Integer.parseInt(appointid));
            Date begin=dataitem.getStartTime();
            Date end=dataitem.getEndTime();
            if(nowdate.after(CalendarDate.addDate(begin,"min",-30)) && nowdate.before(end))
            {

            }

        }catch (Exception e){
            log.error(e.getMessage());
        }
    }
    public String SendComand(Date app_starttime,Date app_endtime, Integer roomId, String wechat, Boolean isOpenDoor, Boolean iscloseNight2,Integer appointId)
    {
        String sendCommand = "";
        String result = "";
        try
        {
            Integer minute=WebConfig.Minute;
            Integer closSecond=WebConfig.ClosSecond;
            //1.去掉这个房间之前预下发的命令
            QueryWrapper<Middlecommand> delwrapp=new QueryWrapper<>();
            delwrapp.eq("roomId",roomId);
            delwrapp.gt("actionTime",new Date());
            delwrapp.eq("state",0);
            middlecommandService.remove(delwrapp);

            //2.获取房间基础信息
            Room roomdata=roomService.getById(roomId);
            QueryWrapper<Meter> meterwapp=new QueryWrapper<>();
            meterwapp.eq("roomId",roomId);
            List<Meter> meterList=meterService.list(meterwapp);
            List<Integer> meterids=meterList.stream().map(Meter::getId).collect(Collectors.toList());

            QueryWrapper<Command> commandwapp=new QueryWrapper<>();
            commandwapp.in("meterid",meterids);
            List<Command> commands=commandService.list(commandwapp);


            //第1步先开门禁，然设置关门禁时间 1001是门禁
            List<Meter> filterMeter=meterList.stream().filter(f->f.getType().equals(1001)).collect(Collectors.toList());
            for (Meter meteritem:filterMeter) {
                //开门禁
                if (isOpenDoor)
                {
                    List<Command> commands1=commands.stream().filter(f->f.getMeterId()==meteritem.getId() && f.getCommandNo()==1).collect(Collectors.toList());
                    sendCommand=commands1.get(0).getCommand();
                    actionService.SendAction(roomdata.getTopic(),sendCommand,new Date(),1,"开门禁",appointId,meteritem.getId(),1,roomId,roomdata.getShopId());
               }
                //时间到关门禁
                List<Command> commands2=commands.stream().filter(f->f.getMeterId()==meteritem.getId() && f.getCommandNo()==2).collect(Collectors.toList());
                sendCommand=commands2.get(0).getCommand();
                actionService.SendAction(roomdata.getTopic(),sendCommand,app_endtime,0,"关门禁",appointId,meteritem.getId(),2,roomId,roomdata.getShopId());

            }


            //第2.1步 开第1回路，设置第2路开灯时间和设置时间到关闭
            filterMeter=meterList.stream().filter(f->f.getType().equals(1002)).collect(Collectors.toList());
            for (Meter meteritem:filterMeter) {
                //开第1路灯
                if (isOpenDoor)
                {
                    Thread.sleep(WebConfig.WaitSecond);
                    List<Command> commands1=commands.stream().filter(f->f.getMeterId()==meteritem.getId() && f.getCommandNo()==3).collect(Collectors.toList());
                    sendCommand=commands1.get(0).getCommand();
                    actionService.SendAction(roomdata.getTopic(),sendCommand,new Date(),1,"第1路开灯",appointId,meteritem.getId(),3,roomId,roomdata.getShopId());
                }
                //开第2路色灯
                List<Command> commands2=commands.stream().filter(f->f.getMeterId()==meteritem.getId() && f.getCommandNo()==5).collect(Collectors.toList());
                sendCommand=commands2.get(0).getCommand();
                actionService.SendAction(roomdata.getTopic(),sendCommand,CalendarDate.addDate(app_endtime,"min",minute*-1),0,"第2路开灯",appointId,meteritem.getId(),5,roomId,roomdata.getShopId());
                //关第1路照明
                commands2=commands.stream().filter(f->f.getMeterId()==meteritem.getId() && f.getCommandNo()==4).collect(Collectors.toList());
                sendCommand=commands2.get(0).getCommand();
                actionService.SendAction(roomdata.getTopic(),sendCommand,app_endtime,0,"第1路关灯",appointId,meteritem.getId(),4,roomId,roomdata.getShopId());
                //关第2路色灯
                commands2=commands.stream().filter(f->f.getMeterId()==meteritem.getId() && f.getCommandNo()==6).collect(Collectors.toList());
                sendCommand=commands2.get(0).getCommand();
                actionService.SendAction(roomdata.getTopic(),sendCommand,app_endtime,0,"第2路关灯",appointId,meteritem.getId(),6,roomId,roomdata.getShopId());
                //关第2路色灯,马上关的，延长预约的时候需要
                if (iscloseNight2)
                {
                    actionService.SendAction(roomdata.getTopic(),sendCommand,new Date(),1,"第2路关灯",appointId,meteritem.getId(),6,roomId,roomdata.getShopId());
                }
            }


            // 第2.2步  播报语言 时间和关闭射灯一样
            filterMeter=meterList.stream().filter(f->f.getType()==1003).collect(Collectors.toList());
            for (Meter meteritem:filterMeter) {
                //播报语言
                List<Command> commands1=commands.stream().filter(f->f.getMeterId()==meteritem.getId() && f.getCommandNo()==11).collect(Collectors.toList());
                sendCommand=commands1.get(0).getCommand();
                actionService.SendAction(roomdata.getTopic(),sendCommand,CalendarDate.addDate(app_endtime,"min",minute*-1),0,"播报语音",appointId,meteritem.getId(),11,roomId,roomdata.getShopId());
             }


          // 第三步关闭门禁 这个是开门后一会的关闭 1001是门禁
            filterMeter=meterList.stream().filter(f->f.getType()==1001).collect(Collectors.toList());
            for (Meter meteritem:filterMeter) {
                 if(isOpenDoor && closSecond>0)
                 {
                     Thread.sleep(closSecond);
                 }
                List<Command> commands1=commands.stream().filter(f->f.getMeterId()==meteritem.getId() && f.getCommandNo()==2).collect(Collectors.toList());
                sendCommand=commands1.get(0).getCommand();
                actionService.SendAction(roomdata.getTopic(),sendCommand,new Date(),1,"关门禁",appointId,meteritem.getId(),2,roomId,roomdata.getShopId());
            }


        }
        catch(Exception ex)
        {
            log.error(ex.getMessage());
        }
        return result;
    }


}
